package controller;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; 

import model.Account;
import model.data.database.AccountTable;


/** * Servlet implementation class LoginServlet */
public class LoginServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	boolean valid;
	HttpServletRequest request;
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException 
	{
		HttpSession session = request.getSession(true);;
		this.request = request;
		try { 
			valid = this.validateUser(request.getParameter("userName"),request.getParameter("password"));
				if (valid){
					session.setAttribute("currentSessionUser", request.getParameter("userName"));
					session.setAttribute("LoginError", "false");
				} 
				else{
					session.setAttribute("currentSessionUser", null);
					session.setAttribute("LoginError", "true");
				}
			response.sendRedirect("Index.jsp");
		}
		catch (Exception ex) { 
			System.out.println(ex.getMessage());
		}
	}
	
	private boolean validateUser(String userName, String password) {
		AccountTable table = new AccountTable();
		try {
			ArrayList<Account> accounts = (ArrayList<Account>)table.getByUserName(request.getParameter("userName"));
			Account account = accounts.get(0);
			System.out.println(account.getPassword());
			if (account.getPassword().equals(request.getParameter("password"))) {
				return true;
			}
			return false;
		}
		catch(Exception ex){
			System.out.println(ex.getMessage());
			return false;
		}
	}
}
